package com.lghs.stutor;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Home extends Activity implements Alertresponder {

    final private Vital vital = new Vital();
    // Activity variables
    private Bundle b;
    private Intent i;
    private ProgressDialog pDialog;

    // AsyncTask variables
    private HttpGet httpGet;
    private HttpResponse execute;
    private DefaultHttpClient client;
    private InputStream content;

    // Storage variables
    private static String url, username, type, subject, sessionid, firstlaunch;

    // Layout components
    ImageView ivstudent, ivtutor, ivcontinue;
    Spinner spinner_subject;
    ArrayAdapter<String> spinneradapter;
    ArrayList<String> spinItems;
    String s;
    String[] priorsessioninfo;
    ConnectivityManager cm;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.lghs.stutor.R.layout.activity_home);
        declaredcomponents();
        addtotutorlist();
        listeners();
        new initilization().execute();


    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home_menu, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.home_ab_account_info:
                i = new Intent();
                i.setClass(getApplicationContext(), Accountinfo.class);
                i.putExtra("uname", username);
                vital.checkInternetConnection(Home.this, cm);
                finish();
                break;
            case R.id.home_ab_settings:
                i = new Intent();
                i.setClass(getApplicationContext(), Settings.class);
                i.putExtra("uname", username);
                vital.checkInternetConnection(Home.this, cm);
                finish();
                break;
            case R.id.home_ab_logout:
                onBackPressed();
                break;
        }
        return true;
    }


    public void declaredcomponents() {
        b = getIntent().getExtras();
        cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        url = "";
        username = "";
        type = "student";
        subject = "";
        sessionid = "";
        firstlaunch = "yes";
        if (b.getString("firstlaunch") != null)
            firstlaunch = b.getString("firstlaunch");
        username = b.getString("uname");
        ivstudent = (ImageView) findViewById(com.lghs.stutor.R.id.home_imageview_student);
        ivtutor = (ImageView) findViewById(com.lghs.stutor.R.id.home_imageview_tutor);
        ivcontinue = (ImageView) findViewById(com.lghs.stutor.R.id.home_imageview_continue);
        spinner_subject = (Spinner) findViewById(com.lghs.stutor.R.id.student_spinner_subject);
        spinItems = new ArrayList<String>();
        spinneradapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_checked, spinItems);
        spinner_subject.setAdapter(spinneradapter);
        ivtutor.setImageResource(R.drawable.tutor1);
        ivstudent.setImageResource(R.drawable.student2);
        ivcontinue.setImageResource(com.lghs.stutor.R.drawable.ft1);
    }

    public void nullimages(boolean newactivty) {
        ivstudent.setImageBitmap(null);
        ivtutor.setImageBitmap(null);
        ivcontinue.setImageBitmap(null);
        System.gc();
    }

    public void listeners() {

        ivstudent.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                nullimages(false);
                ivstudent.setImageResource(R.drawable.student2);
                ivtutor.setImageResource(R.drawable.tutor1);
                ivcontinue.setImageResource(com.lghs.stutor.R.drawable.ft1);
                // btncontinue.setText("Click me to pick your tutor!");
                type = "student";
            }
        });
        ivtutor.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                nullimages(false);
                ivtutor.setImageResource(R.drawable.tutor2);
                ivstudent.setImageResource(R.drawable.student1);
                ivcontinue.setImageResource(com.lghs.stutor.R.drawable.bt2);
                // btncontinue.setText("Click me to start tutoring!");
                type = "tutor";
            }
        });


        ivcontinue.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                if (!subject.equals("")) {
                    if (type.equals("student")) {
                        i = new Intent();
                        i.setClass(getApplicationContext(), Selecttutor.class);
                        i.putExtra("uname", username);
                        i.putExtra("type", type);
                        i.putExtra("subject", subject);
                        startActivity(i);
                        finish();
                    } else
                        new entersession().execute();
                } else //If internet dies call reinit.
                    vital.alertsystem(Home.this, "Missing Subject",
                            "A new list of subjects will be populated", "3", "red", "", "",
                            "Okay");
            }

        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        nullimages(true);
    }

    public void addtotutorlist() {

        spinner_subject.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                subject = (String) spinner_subject.getItemAtPosition(arg2);
                if (subject != null) {
                    subject = subject.replace(" ", "%20");
                }
            }

            public void onNothingSelected(AdapterView<?> parentView) {
                subject = "";
            }
        });
    }

    public void onBackPressed() {
        vital.alertsystem(Home.this, "Logout?", "Are you sure you want to logout?", "23", "idk", "", "Yes", "No");
    }

    private class initilization extends AsyncTask<String, Void, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Home.this, R.style.Theme_MyDialog);
            pDialog.setTitle("You will now wait!");
            pDialog.setIcon(com.lghs.stutor.R.drawable.idk);
            pDialog.setMessage("Loading Subjects\nPlease Wait..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... urls) {

            spinItems.clear();
            String response = "";
            url = "http://" + vital.host + "/getsubjects.php";

            try {

                client = new DefaultHttpClient();
                httpGet = new HttpGet(url);
                execute = client.execute(httpGet);
                content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                s = "";
                while ((s = buffer.readLine()) != null) {
                    s = s.trim();
                    spinItems.add(s);
                }
                if (firstlaunch.equals("yes")) {
                    url = "http://" + vital.host + "/activesessions.php?u=" + username;
                    client = new DefaultHttpClient();
                    httpGet = new HttpGet(url);
                    execute = client.execute(httpGet);
                    content = execute.getEntity().getContent();

                    buffer = new BufferedReader(
                            new InputStreamReader(content));
                    s = "";
                    priorsessioninfo = new String[4];
                    int count = 0;
                    while ((s = buffer.readLine()) != null) {
                        s = s.trim();
                        response = s;
                        priorsessioninfo[count] = s;
                        count++;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        protected void onPostExecute(String result) {
            spinneradapter.notifyDataSetChanged();
            pDialog.dismiss();
            if (!result.equals(""))
                vital.alertsystem(Home.this, "Active Session", "The sessionID: " + priorsessioninfo[0] + "\nUser: " + priorsessioninfo[1] + "\nSubject: " + priorsessioninfo[2] + "\nType: " + priorsessioninfo[3] + "\nis still active", "13", "yellow", "Rejoin", "Ignore", "");
        }
    }

    /* ---Tutor---*/
    private class entersession extends AsyncTask<String, Void, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Home.this, R.style.Theme_MyDialog);
            pDialog.setMessage("Creating your Session");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.setTitle("Creating Session");
            pDialog.setIcon(com.lghs.stutor.R.drawable.idk);
            pDialog.show();
        }

        protected String doInBackground(String... urls) {
            String response = "";
            url = "http://" + vital.host + "/createsession.php?u=" + username
                    + "&s=" + subject; // Change variable subject
            client = new DefaultHttpClient();
            httpGet = new HttpGet(url);
            try {
                HttpResponse execute = client.execute(httpGet);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                s = "";
                while ((s = buffer.readLine()) != null) {
                    response += s;
                    sessionid = s.trim();
                }
                i = new Intent();
                i.setClass(getApplicationContext(), Session.class);
                i.putExtra("uname", username);
                i.putExtra("sessionid", sessionid);
                i.putExtra("type", type);
                i.putExtra("subject", subject);

                vital.checkInternetConnection(Home.this, cm);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        protected void onPostExecute(String result) {
            startActivity(i);
            finish();
            pDialog.dismiss();
        }
    }

    @Override
    public void buttonhandler(int number) {
        switch (number) {
            case 1:
                i = new Intent();
                i.putExtra("uname", username);
                i.putExtra("sessionid", priorsessioninfo[0]);
                i.putExtra("type", priorsessioninfo[3]);
                i.putExtra("subject", priorsessioninfo[2]);
                if (type.equals("student"))
                    i.putExtra("tutorname", priorsessioninfo[1]);
                i.setClass(this, Session.class);
                startActivity(i);
                break;
            case 2:
                Intent i = new Intent(getApplicationContext(), Login.class);
                startActivity(i);
                finish();
                break;
        }

    }

    @Override
    public void internethandler(int number) {
        switch (number) {
            case 1:
                startActivity(i);
                break;
            case 2:
                vital.alertsystem(Home.this, "Internet Connectivity",
                        "Your internet connection seems to be missing", "3",
                        "red", "", "", "Try Again");
                new initilization().execute();
                break;
        }

    }
}